package com.cskaoyan.transfer;

import com.cskaoyan.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

// 转账案例
public class TransferDemo {

    public static void main(String[] args){
        transfer("风华哥","长风",1000);
    }


    // 转账
    public static void transfer(String fromName,String toName,int money){

        Connection connection = JDBCUtils.getConnection();
        PreparedStatement preparedStatement = null;
        PreparedStatement preparedStatement2 = null;

        try {
            // 开启事务
            connection.setAutoCommit(false);

            // 扣钱
            preparedStatement = connection.prepareStatement("update account set money = money - ? where name = ? and money >= ?");

            preparedStatement.setInt(1, money);
            preparedStatement.setString(2, fromName);
            preparedStatement.setInt(3, money);

            int affecteRows = preparedStatement.executeUpdate();

            if (affecteRows > 0) {

                System.out.println("扣钱成功");

            } else {

                System.out.println("扣钱失败！");
                return;

            }

            int i = 1 / 0;

            // 加钱
            preparedStatement2 = connection.prepareStatement("update account set money = money + ? where name = ?");

            preparedStatement2.setInt(1, money);
            preparedStatement2.setString(2, toName);

            int affecteRows2 = preparedStatement2.executeUpdate();

            if (affecteRows2 > 0) {

                System.out.println("加钱成功");

                // 提交事务
                connection.commit();

            } else {

                System.out.println("加钱失败！");

            }
        }catch (Exception ex) {
            ex.printStackTrace();

            // 回滚事务
            try {
                connection.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        try {
            if (preparedStatement2 != null) {
                preparedStatement2.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        JDBCUtils.closeResources(connection,preparedStatement,null);

    }

}

